﻿#include "vipdialog.h"
#include "sqlmanage.h"
#include "vipeditdialog.h"
#include <QDebug>
#include <QMessageBox>
VipDialog::VipDialog(QWidget *parent, MainWindow *_MainWindow) :
    QDialog(parent),
    ui(new Ui::VipDialog),
    vMainWindow(_MainWindow)
{
    ui->setupUi(this);
    Qt::WindowFlags flags=Qt::Dialog;
    flags |=Qt::WindowMinMaxButtonsHint;//显示最大化最小化按钮
    flags |=Qt::WindowCloseButtonHint;//显示关闭按钮
    setWindowFlags(flags);
    //setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);
    //setFixedSize(this->width(), this->height());//固定窗口大小
    QDateTime current_date_time=QDateTime::currentDateTime();
    QString current_date=current_date_time.toString("yyyy.MM.dd hh:mm:ss ddd");
    ui->day_label->setText(current_date);
    ui->vip_pushButton->setEnabled(false);
    ui->vip_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);  //设置选择模式，选择单行
    ui->vip_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);   //设置选择行为，以行为单位
    ui->vip_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);    //不可编辑
    ui->vip_tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->pushButton_pre->setEnabled(false);
    this->init();
    if(pageTotal==1){
        ui->pushButton_next->setEnabled(false);
        ui->pushButton_pre->setEnabled(false);
    }
}

VipDialog::~VipDialog()
{
    qDebug()<<u8"VipDialog 资源释放";
    delete ui;
}
void VipDialog::closeEvent(QCloseEvent *event)
{
    event = event;
    //TODO: 在退出窗口之前，实现希望做的操作
    emit vipClose(0);
}

void VipDialog::on_sales_pushButton_clicked()
{
    vMainWindow->sdlg->show();
    this->close();
}

void VipDialog::on_purchase_pushButton_clicked()
{
    vMainWindow->pdlg->show();
    this->close();
}

void VipDialog::on_exit_pushButton_clicked()
{
    vMainWindow->edlg->show();
    this->close();
}

void VipDialog::updata_time()
{
    ui->day_label->setText(QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss ddd"));
}
/*************************************************************
* @projectName   Test
* @brief         VipDialog::update_vipinfo
*                刷新界面中的数据
* @param[in]     *_result           要显示的结果集指针
* @author        liyih
* @date          2018-07-06
**************************************************************/
void VipDialog::update_vipinfo(QList<Record> *date)
{
    ui->vip_tableWidget->clearContents();   //先清除掉之前的数据
    ui->vip_tableWidget->setRowCount(0);    //重置总行数为0，因为上一句没把size置为0
    ui->vip_tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);  //先固定大小以提高渲染速度
    ui->vip_tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);

    if(date==NULL){
        //this->init();
        date = new QList<Record>;
        *date = dateNow;
    }
    else{
        //dateNow = *_date;
    }
    ui->vip_tableWidget->setRowCount(date->size());
    for(int i = 0; i < date->size(); i++){
        int curRow = ui->vip_tableWidget->currentRow()+1;   //从第0行插入
        curRow = i;
        //int curRow = ui->vip_tableWidget->currentRow();
        //ui->vip_tableWidget->insertRow(curRow);
        QTableWidgetItem *item1 = new QTableWidgetItem((*date)[i].id);
        QTableWidgetItem *item2 = new QTableWidgetItem((*date)[i].vip_name);
        QTableWidgetItem *item3 = new QTableWidgetItem((*date)[i].vip_phone);
        QTableWidgetItem *item4 = new QTableWidgetItem((*date)[i].vip_address);
        QTableWidgetItem *item5 = new QTableWidgetItem((*date)[i].vip_grade);
        QTableWidgetItem *item6 = new QTableWidgetItem((*date)[i].vip_integral);
        QTableWidgetItem *item7 = new QTableWidgetItem((*date)[i].consumption);
        QTableWidgetItem *item8 = new QTableWidgetItem((*date)[i].email);
        QTableWidgetItem *item9 = new QTableWidgetItem((*date)[i].vip_remarks);

        ui->vip_tableWidget->setItem(curRow, 0, item1);
        ui->vip_tableWidget->setItem(curRow, 1, item2);
        ui->vip_tableWidget->setItem(curRow, 2, item3);
        ui->vip_tableWidget->setItem(curRow, 3, item4);
        ui->vip_tableWidget->setItem(curRow, 4, item5);
        ui->vip_tableWidget->setItem(curRow, 5, item6);
        ui->vip_tableWidget->setItem(curRow, 6, item7);
        ui->vip_tableWidget->setItem(curRow, 7, item8);
        ui->vip_tableWidget->setItem(curRow, 8, item9);
    }
    ui->vip_tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);    //行宽可自由拖动
    ui->vip_tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->vip_tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);   //行宽自适应内容
    ui->vip_tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->vip_tableWidget->repaint(); //界面立刻重绘，否则加载很卡顿
}

void VipDialog::init(QString field)
{
    dateNow.clear();
    dateForword.clear();
    this->pageNow = 1;
    qDebug()<<"PageNow->:"<<pageNow;
    dateNow.clear();
    SqlManage conn;
    QSqlQuery queryNow = conn.queryGetPage("vip", 1, field);
    queryNow.setForwardOnly(true);
    while(queryNow.next()){
        Record *record = new Record(&queryNow);
        dateNow.append(*record);
        delete record;
    }
    queryNow = conn.queryGetPage("vip", 2, field);
    while(queryNow.next()){
        Record *record = new Record(&queryNow);
        dateForword.append(*record);
        delete record;
    }
    this->pageTotal = conn.getTotalPage("vip");
    ui->lineEdit_2->setText(QString("%1/%2").arg(pageNow).arg(pageTotal));
    conn.closeSql();
}
/*************************************************************
* @projectName   Test
* @brief         VipDialog::on_add_pushButton_clicked
*                添加一个新的项目
* @param[in]     value
* @param[out]    value
* @author        liyih
* @date          2018-07-06
**************************************************************/
void VipDialog::on_add_pushButton_clicked()
{
    //为避免关闭对话框时主窗口被关闭必须传入this指针，或者采用main（）函数中的策略
    VipEditDialog *editDlg = new VipEditDialog(this);
    editDlg->setWindowTitle(u8"VIP信息添加");
    editDlg->setEditMode(true);
    editDlg->exec();
    SqlManage conn;
    this->pageTotal =  conn.getTotalPage("vip");
    conn.closeSql();
    this->init();
    this->update_vipinfo();
    delete editDlg;
    ui->lineEdit_2->setText(QString("%1/%2").arg(pageNow).arg(pageTotal));
}
/*************************************************************
* @projectName   Test
* @brief         VipDialog::on_modify_pushButton_clicked
*                根据ID修改选中项的值
* @author        liyih
* @date          2018-07-06
**************************************************************/
void VipDialog::on_modify_pushButton_clicked()
{
    //为避免关闭对话框时主窗口被关闭必须传入this指针，或者采用main（）函数中的策略
    VipEditDialog *editDlg = new VipEditDialog(this);
    editDlg->setWindowTitle(u8"VIP信息修改");
    editDlg->setEditMode(false);
    //判断是否选中一行
    bool focus = ui->vip_tableWidget->isItemSelected(ui->vip_tableWidget->currentItem());
    if(focus){
        int row = ui->vip_tableWidget->currentItem()->row();
        QList<QString>info;
        for(int i = 0; i < ui->vip_tableWidget->columnCount(); i++){
            info.append(ui->vip_tableWidget->item(row, i)->text());
            //qDebug()<<ui->vip_tableWidget->item(row, i)->text();
        }
        editDlg->setInfo(info);
        editDlg->setSelectedItemRow(row);
        editDlg->exec();
        SqlManage conn;
        this->pageTotal =  conn.getTotalPage("vip");
        conn.closeSql();
        this->init();
        this->update_vipinfo();
    }
    delete editDlg;
}
/*************************************************************
* @projectName   Test
* @brief         VipDialog::on_cel_pushButton_clicked
*                根据ID删除选中的项目
* @author        liyih
* @date          2018-07-06
**************************************************************/
void VipDialog::on_cel_pushButton_clicked()
{
    bool focus = ui->vip_tableWidget->isItemSelected(ui->vip_tableWidget->currentItem());
    if(focus){
        int row = ui->vip_tableWidget->currentItem()->row();
        long long id = ui->vip_tableWidget->item(row, 0)->text().toLongLong();
        SqlManage conn;
        if(conn.delItemById("vip", "id", id)){
            qDebug()<<"del ok";
        }
        else{
            qDebug()<<"del failed";
        }
        this->pageTotal =  conn.getTotalPage("vip");
        conn.closeSql();
        this->init();
        this->update_vipinfo();
    }
    ui->lineEdit_2->setText(QString("%1/%2").arg(pageNow).arg(pageTotal));
}

/*************************************************************
* @projectName   Test
* @brief         VipDialog::on_comboBox_sort_currentIndexChanged
* @param[in]     index              排序类型
* @author        liyih
* @date          2018-07-06
**************************************************************/
void VipDialog::on_comboBox_sort_currentIndexChanged(int index)
{
    QString key="";
    QString field[4]={"","id", "vip_integral", "consumption"};
    switch (index) {
    case 0:
        break;
    case 1:
        key = field[1];
        break;
    case 2:
        key = field[2];
        break;
    case 3:
        key = field[3];
        break;
    default:
        break;
    }
    this->pageNow = 1;
    this->init(key);
    this->update_vipinfo(&dateNow);
}

void VipDialog::on_pushButton_pre_clicked()
{
    this->update_vipinfo(&datePrevious);
    this->pageNow--;
    ui->lineEdit_2->setText(QString("%1/%2").arg(pageNow).arg(pageTotal));
    if(this->pageTotal != this->pageNow){
        ui->pushButton_next->setEnabled(true);
    }
    if(this->pageNow==1){
        ui->pushButton_pre->setEnabled(false);
    }
    qDebug()<<"PageNow->:"<<pageNow;
    SqlManage conn;
    int sortType = ui->comboBox_sort->currentIndex();
    QString tableName = "vip";
    QString field = "";
    dateForword.clear();
    dateForword = dateNow;
    dateNow.clear();
    dateNow = datePrevious;
    switch (sortType) {
    case 0:
        break;
    case 1:
        field = "id";
        break;
    case 2:
        field = "vip_integral";
        break;
    case 3:
        field = "consumption";
        break;
    default:
        break;
    }
    QSqlQuery queryNow = conn.queryGetPage(tableName, pageNow-1, field);
    queryNow.setForwardOnly(true);
    datePrevious.clear();
    while(queryNow.next()){
        Record *record = new Record(&queryNow);
        datePrevious.append(*record);
        delete record;
    }
    conn.closeSql();
}

void VipDialog::on_pushButton_next_clicked()
{
    this->update_vipinfo(&dateForword);
    this->pageNow++;
    ui->lineEdit_2->setText(QString("%1/%2").arg(pageNow).arg(pageTotal));
    qDebug()<<"PageNow->:"<<pageNow;
    if(this->pageTotal != 1){
        ui->pushButton_pre->setEnabled(true);
    }
    if(this->pageNow == this->pageTotal){
        ui->pushButton_next->setEnabled(false);
    }
    SqlManage conn;
    QString tableName = "vip";
    QString field = "";
    datePrevious.clear();
    datePrevious = dateNow;
    dateNow.clear();
    dateNow = dateForword;
    int sortType = ui->comboBox_sort->currentIndex();
    switch (sortType) {
    case 0:
        break;
    case 1:
        field = "id";
        break;
    case 2:
        field = "vip_integral";
        break;
    case 3:
        field = "consumption";
        break;
    default:
        break;
    }

    QSqlQuery queryNow = conn.queryGetPage(tableName, pageNow+1, field);
    queryNow.setForwardOnly(true);
    dateForword.clear();
    while(queryNow.next()){
        Record *record = new Record(&queryNow);
        dateForword.append(*record);
        delete record;
    }
    conn.closeSql();
}

void VipDialog::on_pushButton_goto_clicked()
{
    SqlManage conn;
    QSqlQuery result;
    QString field = "";
    result.setForwardOnly(true);
    datePrevious.clear();
    dateNow.clear();
    dateForword.clear();
    int toPage = ui->lineEdit_2->text().toInt();
    if(toPage < 1 || toPage > pageTotal){
        QMessageBox::warning(this,u8"提示", u8"请输入正确的页数!", QMessageBox::Yes);
        conn.closeSql();
        return;
    }
    int sortType = ui->comboBox_sort->currentIndex();
    switch (sortType) {
    case 0:
        break;
    case 1:
        field = "id";
        break;
    case 2:
        field = "vip_integral";
        break;
    case 3:
        field = "consumption";
        break;
    default:
        break;
    }
    result = conn.queryGetPage("vip", toPage, field);
    while(result.next()){
        Record *record = new Record(&result);
        dateNow.append(*record);
        delete record;
    }
    this->update_vipinfo();
    this->pageNow = toPage;
    ui->lineEdit_2->setText(QString("%1/%2").arg(pageNow).arg(pageTotal));
    if(pageNow != 1 && pageNow != pageTotal){
        ui->pushButton_pre->setEnabled(true);
        ui->pushButton_next->setEnabled(true);
    }
    else if(pageNow == pageTotal){
        ui->pushButton_pre->setEnabled(true);
        ui->pushButton_next->setEnabled(false);
    }
    else{
        ui->pushButton_pre->setEnabled(false);
        ui->pushButton_next->setEnabled(true);
    }
    result = conn.queryGetPage("vip", toPage-1, field);
    while(result.next()){
        Record *record = new Record(&result);
        datePrevious.append(*record);
        delete record;
    }
    result = conn.queryGetPage("vip", toPage+1, field);
    while(result.next()){
        Record *record = new Record(&result);
        dateForword.append(*record);
        delete record;
    }
    conn.closeSql();
}

void VipDialog::on_pushButton_search_clicked()
{
    QString field;
    QString keyword;
    int searchType = 0;
    keyword = ui->lineEdit->text();
    searchType = ui->comboBox_searchBy->currentIndex();
    if(keyword==""){
        return;
    }
    switch (searchType) {
    case 0:
        field = "id";
        break;
    case 1:
        field = "vip_phone";
        break;
    case 2:
        field = "vip_name";
        break;
    default:
        break;
    }
    SqlManage conn;
    QSqlQuery result;
    result.setForwardOnly(true);
    result = conn.queryTable("vip", field, keyword);
    QList< Record >res;
    while(result.next()){
        Record *record = new Record(&result);
        res.append(*record);
        delete record;
    }
    this->update_vipinfo(&res);
    conn.closeSql();
}
